#include "servicedao_file_impl.h"
#include <fstream>
void ServiceDao_impl::load(vector<Department>& data)
{
	chdir("data");
    fstream fin("services.dat",ios::in|ios::binary);
    //检查打开失败
    char bufdept[MAX_STRING];
    while(fin.getline(bufdept,MAX_STRING))
    {
        fin.seekg(1,ios::cur);//跳过\n
        int id=0;
        char name[20]="";
        int number=0;
        sscanf(bufdept,"%d %s %d",&id,name,&number);
		
        Department dept(id,name);//读取时候赋予人数，后面的add_emp()也会添加人数所以造成双倍人数
        for(int i=0;i<number;i++)
        {
            fin.getline(bufdept,MAX_STRING);
            fin.seekg(1,ios::cur);//跳过\n
            int e_id=0;
            char e_name[20]="";
            int e_gender=0;
            int e_age=0;
            sscanf(bufdept,"%d %s %d %d",&e_id,e_name,&e_gender,&e_age);
            Employee emp(e_id,e_name,e_gender,e_age);
            dept.add_emp(emp);
        }
		if(number==dept.get_d_number())//检查人数
		{
			cout<<"ID:"<<dept.get_d_nId()<<" 加载成功"<<endl;
		}
        m_vecDepts.push_back(dept);
    }
    fin.close();
    
    
}
void ServiceDao_impl::save(vector<Department>& data)
{ 
	chdir("data");
    fstream fout("services.dat",ios::out|ios::binary);
    //检查打开失败
    for(int i=0;i<m_vecDepts.size();i++)
    {
        char bufdept[MAX_STRING];
		int id = m_vecDepts[i].get_d_nId();
		char name[20];
		strcpy(name,m_vecDepts[i].get_d_strName().c_str());

		int number=m_vecDepts[i].get_d_number();
		
        sprintf(bufdept,"%d %s %d\n",id,name,number);

        fout.write(bufdept,strlen(bufdept)+1); 
        for(int j=0;j<m_vecDepts[i].get_d_number();j++)
        {
            char bufemps[MAX_STRING];

			int e_id =m_vecDepts[i].get_index_emp(j).get_m_nId();
			char e_name[20];
			strcpy(e_name,m_vecDepts[i].get_index_emp(j).get_m_strName().c_str());
			int e_gender = m_vecDepts[i].get_index_emp(j).get_m_bGender();
			int e_age=(int)m_vecDepts[i].get_index_emp(j).get_m_nAge();

            sprintf(bufemps,"%d %s %d %d\n",e_id,e_name,e_gender,e_age);
            fout.write(bufemps,strlen(bufemps)+1);
        }
    }
    fout.close();
}
